#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#define PORT 8080
#define BUFFER_SIZE 4096
#define SERVER_IP "127.0.0.1"
void
fatal(char *string)
{
    printf("%s\n",string);
    exit(1);
}

int main(int argc, char  **argv) {
    int sock = 0, valread,len,end_flag=0,i;
    struct sockaddr_in serv_addr;
    char buffer[BUFFER_SIZE] = {0};
    char input[BUFFER_SIZE] = {0};
    //if(argc !=3 ) fatal("Usage: client server-name file-name");
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        exit(EXIT_FAILURE);
    }
    memset(&serv_addr,0,sizeof(serv_addr));
    
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serv_addr.sin_port = htons(PORT);
    


    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("Connection Failed");
        exit(EXIT_FAILURE);
    }

    printf("Connected to server\n");
    
    while (1) {
    	int opt;

    	    int index=0;
    	    char c;
            printf("enter message , end with double Enter:\n");
            while(1){
		if(index>=BUFFER_SIZE-3){    //一个缓冲区满
		    buffer[index]='\0';
		    printf("this buffer is: \n%s\n",buffer);
		    send(sock,buffer,strlen(buffer),0);
		    memset(buffer,0,BUFFER_SIZE);
		    index=0;
		}
            	c=getchar();
            	if(c=='\n'){             //连续两次回车结束输入
            	    buffer[index]=c;
            	    index++;
            	    c=getchar();
            	    if(c=='\n'){
            	        buffer[index]=c;
            	        index++;
            	        break;
            	    }
            	}
            	buffer[index]=c;
            	index++;
            }
            buffer[index]='\0';
            printf("this server told me it get:\n");
            send(sock,buffer,strlen(buffer),0);
            
            valread=read(sock,buffer,BUFFER_SIZE);
	    if(valread<=0) exit(0);
	    write(1,buffer,valread);
            printf("\n");
            memset(buffer,0,BUFFER_SIZE);

    }

    return 0;
}




